/**
 * 获取基础链接
 */
function getBaseUrl() {
	// #ifdef MP-WEIXIN
	switch (__wxConfig.envVersion) {
		case 'develop':
			return 'http://localhost:8080'; //测试版
			break;
		case 'trial':
			return 'http://localhost:8080'; //体验版
			break;
		case 'release':
			return 'http://localhost:8080'; //线上
			break;
		default:
			return 'http://localhost:8080';
	}
	// #endif
	
	// #ifdef H5
	return 'http://localhost:8080'; //测试版
	// #endif
}

/**
 * 获取http链接
 */
function getHttpUrl() {
	return getBaseUrl() + "/server"
}

/**
 * 普通请求
 * @param {Object} url
 * @param {Object} options
 */
function request(url, options) {
	console.info("请求参数", url, options)
	//是否展示【加载中...】
	if (options.isToast) {
		uni.$common.toastLoading()
	}
	return new Promise((resolve, reject) => {
		console.info("进行网络请求", url, options.data)
		uni.request({
			url: getHttpUrl() + `${url}`,
			method: options.method,
			data: options.data,
			header: {
				'authorization': "Bearer_" + uni.getStorageSync("token"),
				'client': uni.getSystemInfoSync().uniPlatform,
			},
			success: (res) => {
				console.info("网络请求成功", url, res)
				if (res.statusCode == 200) {
					requestSuc(url, options, res, resolve, reject)
				} else {
					requestFail(url, res, reject)
				}
			},
			fail: (error) => {
				requestFail(url, error, reject)
			}
		})
	})
}

/**
 * 上传文件
 * @param {Object} url
 * @param {Object} options
 * @param {Object} config
 */
function httpUpFile(url, options, config) {
	options = setOptions('POST', 'UPLOAD_FILE', options, config)
	console.info("上传文件参数", url, options)
	if (options.isToast) {
		uni.$common.toastLoading()
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: getHttpUrl() + `${url}`,
			filePath: options.data.file,
			name: 'file',
			formData: {
				rootPath: "app/" + options.data.rootPath
			},
			header: {
				'authorization': "Bearer_" + uni.getStorageSync("token"),
				'client': uni.getSystemInfoSync().uniPlatform
			},
			success: (res) => {
				console.info("网络请求成功", url, res)
				if (res.statusCode == 200) {
					res.data = JSON.parse(res.data)
					requestSuc(url, options, res, resolve, reject)
				} else {
					requestFail(url, res, reject)
				}
			},
			fail: (error) => {
				requestFail(url, error, reject)
			}
		});
	})
}

/**
 * 请求成功的处理
 * @param {Object} url
 * @param {Object} options
 * @param {Object} requestData
 * @param {Object} resolve
 * @param {Object} reject
 */
function requestSuc(url, options, requestData, resolve, reject) {
	if (options.isToast) {
		uni.$common.toastHide()
	}

	if (requestData.data.code == 200) {
		resolve(requestData.data.result)
	} else if (requestData.data.code == 401 && !options.isLoginRequest) {
		//需要登录
		uni.removeStorageSync("token")
		//进行登录，登录后继续执行请求
		login((result) => {
			if (result) {
				uni.$emit("login")
				if (options.type == "UPLOAD_FILE") {
					resolve(httpUpFile(url, options))
				} else {
					resolve(request(url, options))
				}
			}else{
				reject(requestData.data)
			}
		})
	} else if (requestData.data.code == 401 && options.isLoginRequest) {
		//登录接口登录失败
		if (requestData.data.message) {
			uni.$common.toastNone(requestData.data.message)
		}
		reject(requestData.data)
	} else {
		if (requestData.data.message) {
			uni.$common.toastNone(requestData.data.message)
		}
		reject(requestData.data)
	}
}

/**
 * 请求失败的处理
 * @param {Object} url
 * @param {Object} error
 * @param {Object} reject
 */
function requestFail(url, error, reject) {
	console.error("网络请求失败", url, error)
	uni.$common.toastHide()
	uni.$common.toastNone("请求失败，请检查网络或联系管理员." + error.errMsg)
	reject(error.data)
}

/**
 * 设置请求参数
 * @param {Object} method 请求方式
 * @param {Object} type 成功处理类型。正常请求、上传文件
 * @param {Object} options	请求参数
 * @param {Object} config	请求配置
 */
function setOptions(method, type, options, config) {
	if (!options) {
		options = {}
	}
	if (config) {
		if (!config.hasOwnProperty("isToast")) {
			config.isToast = true
		}
		if (!config.hasOwnProperty("isLoginRequest")) {
			config.isLoginRequest = false
		}
	} else {
		config = {
			isToast: true,
			isLoginRequest: false
		}
	}

	return {
		method: method,
		type: type,
		data: options,
		isToast: config.isToast,
		isLoginRequest: config.isLoginRequest
	}
}

/**
 * 登录方法
 */
function login(event) {
	//小程序无感登录
	uni.login({
		success: res => {
			if (res.code) {
				uni.$api.userLogin({
					code: res.code,
				}).then((data) => {
					uni.setStorageSync('token', data.token)
					uni.setStorageSync('userInfo', data.userInfo)
					event(true)
				})
			}
		},
		fail: (e) => {
			console.info("登录失败", e)
			event(false);
		}
	})
	//跳转到登录页面
	// uni.$common.modalInfo("您还没有登录，请先登录",()=>{
	// 	//这里跳转到登录页
	// 	uni.$common.navTo("/subpkg/commons/login/login")
	// },()=>{})
}


/**
 * GET请求。查询
 * @param {Object} url
 * @param {Object} options
 * @param {Object} config
 */
function httpGet(url, options, config) {
	return request(url, setOptions('GET', 'REQUEST', options, config))
}

/**
 * POST请求。添加/修改
 * @param {Object} url
 * @param {Object} options
 * @param {Object} config
 */
function httpPost(url, options, config) {
	return request(url, setOptions('POST', 'REQUEST', options, config))
}

/**
 * DELETE请求。删除
 * @param {Object} url
 * @param {Object} options
 * @param {Object} config
 */
function httpDelete(url, options, config) {
	return request(url, setOptions('DELETE', 'REQUEST', options, config))
}

export default {
	getHttpUrl: getHttpUrl,
	getBaseUrl: getBaseUrl,
	get: httpGet,
	post: httpPost,
	delete: httpDelete,
	uploadFile: httpUpFile
}